package com.springbootweb.springbootweb.controller;

import com.springbootweb.springbootweb.dao.DepartmentDao;
import com.springbootweb.springbootweb.dao.EmployeeDao;
import com.springbootweb.springbootweb.entities.Department;
import com.springbootweb.springbootweb.entities.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

@Controller
public class EmployeeController {
    @Autowired
    EmployeeDao employeeDao;
    @Autowired
    DepartmentDao departmentDao;
    // 查询员工列表
    @GetMapping("/emps")
    public String list(Model model){
        Collection<Employee> employees = employeeDao.getAll();
        // 放在请求域中
        model.addAttribute("emps",employees);
        // 默认拼创
        return "emp/list";
    }

    // 跳转到添加员工页面
    @GetMapping("/emp")
    public String toAddPage(Model model){
        // 来到添加页面 查出所有部门在页面显示
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("depts",departments);
        return "emp/add";
    }

    // 添加员工
    @PostMapping("/emp")
    public String addEmp(Employee employee){
        employeeDao.save(employee);
        return "redirect:/emps";
    }

    // 来到修改页面
    @GetMapping("/emp/{id}")
    public String toEditPage(@PathVariable("id") Integer id,Model model){
        Employee employee = employeeDao.get(id);
        model.addAttribute("emp",employee);
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("depts",departments);
        // 回到修改页面
        return "emp/add";
    }

    // 员工修改 需要提交员工id
    @PutMapping("/emp/{id}")
    public String updataEmp(Employee employee){
        employeeDao.save(employee);
        return "redirect:/emps";
    }

   // 员工删除
    @DeleteMapping("/emp/{id}")
    public String deleteEmp(@PathVariable("id") Integer id){
        employeeDao.delete(id);
        return "redirect:/emps";
    }
}
